package bb.lanxing.net.core;

import bb.lanxing.net.okhttp.OkHttpApiClient;
import bb.lanxing.net.okhttp.OkRequestConvert;
import bb.lanxing.net.okhttp.OkResponseConvert;
import java.io.IOException;
import okhttp3.Response;
import rx.Observable;
import rx.functions.Func1;

public class DefaultApiClient extends ApiClientWrapper<okhttp3.Request, Response> {
    private final OkHttpApiClient client;
    protected ApiClientConfig config;
    private final OkRequestConvert requestConvert;
    private final OkResponseConvert responseConvert;

    public DefaultApiClient(ApiClientConfig clientConfig) {
        this(clientConfig, new OkRequestConvert(), new OkResponseConvert());
    }

    public DefaultApiClient(ApiClientConfig clientConfig, OkRequestConvert requestConvert, OkResponseConvert responseConvert) {
        this.client = new OkHttpApiClient(clientConfig);
        this.requestConvert = requestConvert;
        this.responseConvert = responseConvert;
        this.config = clientConfig;
    }

    @Override
    public okhttp3.Request convert(ApiRequest req) {
        return this.requestConvert.convert(req, this.config);
    }

    @Override
    public ApiResponse convert(Response response) {
        return this.responseConvert.convert(response);
    }

    @Override
    public ApiClient<okhttp3.Request, Response> getApiClient() {
        return this.client;
    }

    public Observable<ApiResponse> observable(ApiRequest request) {
        return Observable.just(request).flatMap((Func1<ApiRequest, Observable<ApiResponse>>) request2 -> {
            try {
                return Observable.just(DefaultApiClient.this.execute(request2));
            } catch (IOException e) {
                return Observable.error(e);
            }
        });
    }
}
